package com.antler.luajavalibrary;

import android.app.Application;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.input.InputManager;
import android.os.IBinder;
import android.util.Log;

import com.antler.luajavalibrary.application.MyApplication;
import com.antler.luajavalibrary.inf.IScriptManager;
import com.antler.luajavalibrary.service.ScriptService;
import com.antler.luajavalibrary.utils.FileUtils;

public class ScriptManager implements IScriptManager, IScriptManager.Callback {
    private static final String TAG = "antler_" + ScriptManager.class.getSimpleName();

    private IScriptManager.Callback mCallback = null;

    private ScriptManager() {
    }

    public static IScriptManager getInstance() {
        return ScriptManagerHolder.sInstance;
    }

    private static class ScriptManagerHolder {
        private static final ScriptManager sInstance = new ScriptManager();
    }

    private ScriptService mScriptService = null;

    private ServiceConnection mServiceConn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.v(TAG, "onServiceConnected name=" + name);
            ScriptService.MyBinder binder = (ScriptService.MyBinder) service;
            mScriptService = binder.getService();

            mScriptService.setCallback(ScriptManager.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.v(TAG, "onServiceDisconnected name=" + name);
        }
    };

    @Override
    public boolean init(Application application) {
        MyApplication.setApplication(application);
        Context context = MyApplication.getContext();

        Intent intent = new Intent(context, ScriptService.class);
        context.bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);
        return true;
    }

    @Override
    public void uninit() {
    }

    @Override
    public boolean start(String scriptContent) {
        if (mScriptService != null) {
            mScriptService.start(scriptContent);
            return true;
        }
        return false;
    }

    @Override
    public boolean startWithFile(String filePath) {
        if (mScriptService != null) {
            mScriptService.startWithFile(filePath);
            return true;
        }
        return false;
    }

    @Override
    public void stop() {
        if (mScriptService != null) {
            mScriptService.stop();
        }
    }

    @Override
    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    @Override
    public void SM_print(String msg) {
        if (mCallback != null) {
            mCallback.SM_print(msg);
        }
    }
}